import React, {useRef, useEffect, useState} from "react";
import * as echarts from "echarts";
import geoJson from "@/assets/data/china_geo.json";
import {WeatherHours} from "@/types/weather";
import {RealData} from "@/types/common.ts";
import {convertToBeijingTime} from "@/utils/time.ts";

interface ChinaMapProps {
    data: RealData<WeatherHours[]>;
    width?: string;
    height?: string;
    onClick?: (params: any) => void;
    onMouseOver?: (params: any) => void;
}

interface MapDataSourceProps {
    name: string;
    value: number;
}

export default function ChinaMap({
                                     data,
                                     width = "100%",
                                     height = "100%",
                                     onClick,
                                     onMouseOver,
    
                                 }: ChinaMapProps) {
    const ref = useRef<HTMLDivElement>(null);
    const chartRef = useRef<echarts.ECharts|null>(null);
    const [highestTemperature, setHighestTemperature] = useState(0);
    const [lowestTemperature, setLowestTemperature] = useState(0);

    const mapStyles : React.CSSProperties = {
        width,
        height,
        minWidth: 400,
        minHeight: 500,
        margin: 10,
        marginTop: 25,
        boxShadow: "0px 4px 10px rgba(0, 0, 0, 0.1)",
        overflow: "hidden"
    }

    useEffect(() => {
        if (!ref.current) return;

        // 设置最高气温和最低气温指标
        if (!data || data.data.length === 0) return;

        const temps = data.data.map((item) => item.now.temp).filter((v) => typeof v === 'number' && !isNaN(v));
        if (temps.length === 0) return;

        const maxTemp = Math.max(...temps);
        const minTemp = Math.min(...temps);

        setHighestTemperature(maxTemp);
        setLowestTemperature(minTemp);

        // 注册地图数据
        echarts.registerMap("china", geoJson as any);

        // 初始化实例
        if (!chartRef.current) {
            chartRef.current = echarts.init(ref.current);
        }


        // 配置项
        const option = {
            title: [
                {
                    text:  `${convertToBeijingTime(data.updateTime)}更新`,
                    textStyle: { color: "grey" , fontSize: 12 }, // 设置字体颜色为红色
                    left: "left",
                },
                {
                    text: "天气地图",
                    subtext: "全国各省气温",
                    top: "1%",
                    left: "right",
                }
            ],
            tooltip: {
                trigger: "item",
                formatter: (params: MapDataSourceProps) => {
                    const val = params.value;
                    if (isNaN(val)) {
                        return ""; // 不显示 tooltip
                    }
                    return `当前气温：${val}℃`;
                },
            },
            toolbox: {
                show: true,
                left: "left",
                top: "top",
                feature: {
                    restore: false,
                    saveAsImage: false
                },
            },
            series: {
                type: "map",
                map: "china",
                roam: true,
                zoom: 1.5,
                top: "25%",
                label: {
                    show: true,
                    fontSize: 12,
                },
                itemStyle: {
                    areaColor: "#ddd",
                },
                emphasis: {
                    itemStyle: {
                        areaColor: "rgba(51,99,206,0.9)",
                        borderColor: "#4aacd9",
                    },
                },
                data: data.data.map((item) => ({
                    name: item.location.province,
                    value: item.now.temp
                })),
            },
            visualMap: {
                type: "continuous",
                left: "right",
                min: lowestTemperature,
                max: highestTemperature,
                inRange: {
                    color: ['#00cfff', '#10fddd', '#fffb00', '#ff7e00', '#ff0000'], // 蔚蓝到橙色渐变
                },
                text: ["最高气温", "最低气温"],
            },
        };

        chartRef.current.setOption(option);

        if (onClick) chartRef.current.on("click", onClick);
        if (onMouseOver) chartRef.current.on("mouseover", onMouseOver);

        const resizeHandler = () => {
            chartRef.current?.resize();
        };

        window.addEventListener("resize", resizeHandler);

        return () => {
            if (!chartRef.current) {
                chartRef.current?.dispose();
                chartRef.current = null;
            }
            window.removeEventListener("resize", resizeHandler);
        };
    }, [data, highestTemperature, lowestTemperature, onClick, onMouseOver]);

    return (
        <div
            ref={ref}
            style={mapStyles}
        />
    );
}

